﻿using IDAdmin.Common;
using IDAdmin.Lib.DataLayer;
using IDAdmin.Lib.UI;
using IDAdmin.Lib.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace IDAdmin.Pages
{
    public partial class OnlinePeopleNumber : BasePage
    {
        public OnlinePeopleNumber()
            : base(Lib.AppFunctions.ONLINEPEOPLENUMBER)
        {

        }

        private static List<Server> listServer = WebDB_N.ListServer();
        private static List<Ccu> ccuData;
        protected override void Page_Load(object sender, EventArgs e)
        {
            if (!IsLogin())
            {
                RedirectToLogOn();
            }
            else if (!CheckRight())
            {
                RedirectToDeniedMessage();
            }
        }

        /// <summary>
        /// Get online daily - Nhi Tran
        /// </summary>
        /// <returns></returns>
        /// 

        protected void getCcuButton_Click(object sender, EventArgs e)
        {
            DateTime dtFormDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.beginDateTextBox.Text);
            DateTime dtToDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.toDateTextBox.Text);
            List<DateTime> dateTimeList = IDAdmin.Common.ConverterWorkData.getDateListBetween(dtFormDate, dtToDate);
            ccuData = WebDB.getCcu(dateTimeList);
        }


        /// <summary>
        /// Get online daily - Hoa Tran
        /// </summary>
        /// <returns></returns>
        /// 
        private Table
            getCcuRealTime()
        {
            //string _startDate = txtFromDate.Text;
            //string _endDate = txtToDate.Text;
            // IEnumerable<Ccu> ccuList=dt.AsEnumerable().ToList<Ccu>().;

            List<Ccu> dataList = new List<Ccu>(ccuData.Count);

            ccuData.ForEach((item) =>
            {
                dataList.Add(new Ccu(item));
            });

            //List<Ccu> dataList = new List<Ccu>(paramDt);//ConverterWorkData.ToList<Ccu>(paramDt).OrderBy(o=>o.Timestamp).ToList();
            foreach (Ccu ccuItem in dataList)
            {
                ccuItem.Timestamp = ConverterWorkData.truncateTime(ccuItem.Timestamp, "dd/MM/yyyy HH:mm");
            }
            //dataList = (from tb in dataList.AsParallel() where ConverterWorkData.ConvertFromUnixTimestamp(double.Parse(tb.Timestamp)).Minute % 5 == 0 select tb).ToList();
            //dataList = (from tb in dataList.AsParallel() where ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(tb.Timestamp), DateTimeKind.Local, DateTimeKind.Local).Minute % 5 == 0 select tb).ToList();

            var gameZoneListTemp = dataList.AsParallel().Select(s => new { s.GameZone }).Distinct().OrderBy(o => o.GameZone).ToList();
            var gameZoneList = new[] { new { GameZone = "", ZoneName = "" } }.ToDictionary(d => d.GameZone, d => d.ZoneName);
            gameZoneList.Remove("");
            foreach (var zone in gameZoneListTemp)
            {
                if (gameZoneList.Keys.Contains(zone.GameZone) == false)
                {
                    gameZoneList.Add(zone.GameZone, dataList.AsParallel().Where(w => w.GameZone.Equals(zone.GameZone)).FirstOrDefault().ZoneName);
                }
            }
            Dictionary<int, List<Ccu>> gameZoneDataDic = new Dictionary<int, List<Ccu>>();
            for (int i = 0; i < gameZoneList.Count(); i++)
            {
                List<Ccu> gameZoneData = dataList.AsParallel().Where(w => w.GameZone.Equals(gameZoneList.ElementAt(i).Key)).OrderBy(o => o.Timestamp).ToList();
                gameZoneDataDic.Add(int.Parse(gameZoneList.ElementAt(i).Key), gameZoneData);
            }

            var timeList = dataList.AsParallel().OrderByDescending(o => o.Timestamp).Select(s => s.Timestamp).Distinct().ToList();
            //timeList = (from tb in timeList
            //where ConverterWorkData.ConvertFromUnixTimestamp(double.Parse(tb)).Minute % 5 == 0
            //select tb).ToList();
            var ccuPresentList = dataList.AsParallel().GroupBy(c => c.Timestamp).Select(g => new { Timestamp = g.Key, Sum = g.Sum(h => int.Parse(h.Num)) }).OrderBy(o => o.Timestamp).ToList();

            //var ccuDayBefore = dataList.Where(w => w.Timestamp.Equals(ConverterWorkData.ConvertToUnixTimestamp(DateTime.ParseExact(ConverterWorkData.ConvertFromUnixTimestamp(long.Parse(w.Timestamp)).AddDays(-1).ToString("dd/MM/yyyy hh:mm"),"dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture)))).GroupBy(c => c.Timestamp).Select(g => new { Timestamp = (int.Parse(g.Key) + 86400).ToString(), Sum = g.Sum(h => int.Parse(h.Num)) }).OrderBy(o => o.Timestamp).ToList();
            //var CcuSevenDayBefore = dataList.Where(w => w.Timestamp.Equals((int.Parse(w.Timestamp) - 604800).ToString())).GroupBy(c => c.Timestamp).Select(g => new { Timestamp = (int.Parse(g.Key) + 604800).ToString(), Sum = g.Sum(h => int.Parse(h.Num)) }).OrderBy(o => o.Timestamp).ToList();
            //var CcuMonthBefore = dataList.Where(w => w.Timestamp.Equals((int.Parse(w.Timestamp) - 604800).ToString())).GroupBy(c => c.Timestamp).Select(g => new { Timestamp = (int.Parse(g.Key) + 604800).ToString(), Sum = g.Sum(h => int.Parse(h.Num)) }).OrderBy(o => o.Timestamp).ToList();

            List<CcuFiveMinuteOnce> CcuFiveMinuteOnceList = new List<CcuFiveMinuteOnce>();

            for (int i = 0; i < timeList.Count; i++)
            {
                //string strDt= ConverterWorkData.ConvertFromUnixTimestamp(long.Parse(timeList[i])).ToString("dd/MM/yyyy hh:mm");
                //DateTime dtTemp = DateTime.ParseExact(strDt, "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);
                //string timeStampTemp = truncateSecond(timeList[i]);
                CcuFiveMinuteOnce cfmo = new CcuFiveMinuteOnce();
                foreach (KeyValuePair<int, List<Ccu>> entry in gameZoneDataDic)
                {
                    //var ccu = entry.Value.ToArray()[i];
                    Ccu ccu = null;
                    try
                    {
                        ccu = entry.Value.AsParallel().Where(w => w.Timestamp.Equals(timeList[i])).FirstOrDefault();
                        if (ccu == null)
                        {
                            ccu = new Ccu() { GameZone = entry.Key.ToString(), Timestamp = timeList[i], Num = "0" };
                        }
                    }
                    catch (Exception ex)
                    {

                        ccu = new Ccu() { GameZone = entry.Key.ToString(), Timestamp = timeList[i], Num = "0" };
                    }

                    cfmo.CcuServerList.Add(ccu);
                }
                try
                {
                    var ccuPresent = ccuPresentList.AsParallel().Where(w => w.Timestamp.Equals(timeList[i])).Single();
                    cfmo.SumCcuPresent = ccuPresent.Sum.ToString();
                }
                catch (Exception ex)
                {
                    cfmo.SumCcuPresent = "";
                }

                //if (ccuDayBefore.Count > 0)
                // {
                //cfmo.SumCcuDayBefore = ccuDayBefore.ToArray()[i].Sum.ToString();
                //cfmo.SumCcuDayBefore = ccuDayBefore.Where(w => w.Timestamp.Equals(timeList[i])).Select(s=>s.Sum).Single().ToString();

                //string strDateBeforeTs = truncateSecond(dayBeforeTs.ToString());
                try
                {
                    DateTime dayBeforedt = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local).AddDays(-1);
                    long dayBeforeTs = long.Parse(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dayBeforedt, DateTimeKind.Local).ToString());
                    var temp = dataList.AsParallel().Where(w => w.Timestamp.Equals(dayBeforeTs.ToString())).GroupBy(c => c.Timestamp).Select(g => new { Sum = g.Sum(h => int.Parse(h.Num)) }).Single();
                    cfmo.SumCcuDayBefore = temp.Sum.ToString();
                }
                catch (Exception ex)
                {
                    cfmo.SumCcuDayBefore = "";
                }

                try
                {
                    DateTime dayBeforedt = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local).AddDays(-7);
                    long sevenDayBeforeTs = long.Parse(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dayBeforedt, DateTimeKind.Local).ToString());
                    var temp = dataList.AsParallel().Where(w => w.Timestamp.Equals(sevenDayBeforeTs.ToString())).GroupBy(c => c.Timestamp).Select(g => new { Sum = g.Sum(h => int.Parse(h.Num)) }).Single();
                    cfmo.SumCcuSevenDayBefore = temp.Sum.ToString();
                }
                catch (Exception ex)
                {
                    cfmo.SumCcuSevenDayBefore = "";
                }

                try
                {
                    DateTime dayBeforedt = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local).AddDays(-30);
                    long thirtyDayBeforeTs = long.Parse(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dayBeforedt, DateTimeKind.Local).ToString());
                    var temp = dataList.AsParallel().Where(w => w.Timestamp.Equals(thirtyDayBeforeTs.ToString())).GroupBy(c => c.Timestamp).Select(g => new { Sum = g.Sum(h => int.Parse(h.Num)) }).Single();
                    cfmo.SumCcuMonthBefore = temp.Sum.ToString();
                }
                catch (Exception ex)
                {
                    cfmo.SumCcuMonthBefore = "";
                }

                // }
                // if (CcuSevenDayBefore.Count > 0)
                // {
                // cfmo.SumCcuSevenDayBefore = CcuSevenDayBefore.ToArray()[i].Sum.ToString();
                // }
                // if (CcuMonthBefore.Count > 0)
                // {
                //cfmo.SumCcuMonthBefore = CcuMonthBefore.ToArray()[i].Sum.ToString();
                //}
                cfmo.DateTime = ConverterWorkData.kindUnixTimeStampToKindDateTime(long.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                cfmo.Date = UnixTimeStampToDateTime(Convert.ToInt32(timeList[i])).ToString("dd/MM/yy HH:mm");
                cfmo.TimeStamp = long.Parse(timeList[i]);
                CcuFiveMinuteOnceList.Add(cfmo);
            }
            //string startTime = timeList[0];

            //DataTable dt = ConverterWorkData.ToDataTable(CcuFiveMinuteOnceList, 0, gameZoneList.Count());

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Thời gian",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tổng cuu tháng trước",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tổng cuu tuần trước",Unit.Percentage(10),HorizontalAlign.Center, "cellHeader"),  
                    UIHelpers.CreateTableCell("Tổng cuu ngày trước",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    UIHelpers.CreateTableCell("Tổng cuu hiện tại",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                }
            );
            foreach (var zone in gameZoneList)
            {
                rowHeader.Cells.Add(UIHelpers.CreateTableCell(zone.Value, Unit.Percentage(6), HorizontalAlign.Center, "cellHeader"));
            }
            table.Rows.Add(rowHeader);
            try
            {
                if (CcuFiveMinuteOnceList == null || CcuFiveMinuteOnceList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (var dr in CcuFiveMinuteOnceList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                                {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Date),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.SumCcuMonthBefore),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.SumCcuSevenDayBefore), HorizontalAlign.Center, css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.SumCcuDayBefore),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.SumCcuPresent),HorizontalAlign.Center,css)
                                }
                        );
                        foreach (var zone in dr.CcuServerList.OrderBy(o => o.GameZone).ToList())
                        {
                            row.Cells.Add(UIHelpers.CreateTableCell(Converter.ToString(zone.Num), HorizontalAlign.Center, css));
                        }
                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return table;
        }


        public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
        {
            // Unix timestamp is seconds past epoch
            System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
            return dtDateTime;
        }

        private Table getCcuAverage()
        {
            List<Ccu> dataList = new List<Ccu>(ccuData.Count);

            ccuData.ForEach((item) =>
            {
                dataList.Add(new Ccu(item));
            });

            //List<Ccu> dataList = new List<Ccu>(paramDt);
            foreach (Ccu ccuItem in dataList)
            {
                ccuItem.Timestamp = ConverterWorkData.truncateTime(ccuItem.Timestamp, "dd/MM/yyyy");
            }
            var gameZoneListTemp = dataList.AsParallel().Select(s => new { s.GameZone }).Distinct().OrderBy(o => o.GameZone).ToList();
            var gameZoneList = new[] { new { GameZone = "", ZoneName = "" } }.ToDictionary(d => d.GameZone, d => d.ZoneName);
            gameZoneList.Remove("");
            foreach (var zone in gameZoneListTemp)
            {
                if (gameZoneList.Keys.Contains(zone.GameZone) == false)
                {
                    gameZoneList.Add(zone.GameZone, dataList.AsParallel().Where(w => w.GameZone.Equals(zone.GameZone)).FirstOrDefault().ZoneName);
                }
            }
            Dictionary<int, List<Acu>> gameZoneDataDic = new Dictionary<int, List<Acu>>();
            for (int i = 0; i < gameZoneList.Count(); i++)
            {
                List<Acu> gameZoneData = (from tb in dataList where tb.GameZone.Equals(gameZoneList.ElementAt(i).Key) group tb by new { tb.GameZone, tb.Timestamp } into grp select new Acu { GameZone = grp.Key.GameZone, Timestamp = grp.Key.Timestamp, Average = grp.Average(t => long.Parse(t.Num)).ToString("0") }).ToList(); //dataList.GroupBy(g => g.Timestamp, g => g.GameZone).Where(w => w.Key.Equals(gameZoneList.ElementAt(i))).OrderBy(o => o.Timestamp).ToList();
                gameZoneDataDic.Add(int.Parse(gameZoneList.ElementAt(i).Key), gameZoneData);
            }
            var timeList = dataList.OrderByDescending(o => o.Timestamp).Select(s => s.Timestamp).Distinct().ToList();
            //var acuSumList = dataList.GroupBy(c => c.Timestamp).Select(g => new { Timestamp = g.Key, Average = g.Average(h => int.Parse(h.Num)) }).OrderBy(o => o.Timestamp).ToList();

            List<CcuAverage> ccuAverageList = new List<CcuAverage>();

            for (int i = 0; i < timeList.Count; i++)
            {
                //string strDt= ConverterWorkData.ConvertFromUnixTimestamp(long.Parse(timeList[i])).ToString("dd/MM/yyyy hh:mm");
                //DateTime dtTemp = DateTime.ParseExact(strDt, "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);
                //string timeStampTemp = truncateSecond(timeList[i]);
                CcuAverage ca = new CcuAverage();
                foreach (KeyValuePair<int, List<Acu>> entry in gameZoneDataDic)
                {
                    //var ccu = entry.Value.ToArray()[i];
                    Acu acu = null;
                    try
                    {
                        acu = entry.Value.Where(w => w.Timestamp.Equals(timeList[i])).FirstOrDefault();
                        if (acu == null)
                        {
                            acu = new Acu() { GameZone = entry.Key.ToString(), Timestamp = timeList[i], Average = "0" };
                        }
                    }
                    catch (Exception ex)
                    {

                        acu = new Acu() { GameZone = entry.Key.ToString(), Timestamp = timeList[i], Average = "0" };
                    }

                    ca.AverageCcuServerList.Add(acu);
                }
                try
                {
                    var acuSum = (from tb in ca.AverageCcuServerList group tb by new { tb.Timestamp } into grp select new { Average = grp.Sum(t => long.Parse(t.Average)) }).FirstOrDefault();
                    ca.AcuSum = acuSum.Average.ToString();
                }
                catch (Exception ex)
                {
                    ca.AcuSum = "";
                }
                ca.DateTime = ConverterWorkData.kindUnixTimeStampToKindDateTime(long.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                ca.Date = ConverterWorkData.kindUnixTimeStampToKindDateTime(long.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local).ToString("dd/MM/yyyy");
                ca.TimeStamp = long.Parse(timeList[i]);
                ccuAverageList.Add(ca);
            }
            string startTime = timeList[0];

            //DataTable dt = ConverterWorkData.ToDataTable(ccuAverageList, 1, gameZoneList.Count());

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Thời gian",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tổng acu",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                }
            );
            foreach (var zone in gameZoneList)
            {
                rowHeader.Cells.Add(UIHelpers.CreateTableCell(zone.Value, Unit.Percentage(6), HorizontalAlign.Center, "cellHeader"));
            }
            table.Rows.Add(rowHeader);
            try
            {
                if (ccuAverageList == null || ccuAverageList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (var dr in ccuAverageList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                                {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Date),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.AcuSum),HorizontalAlign.Center,css)
                                }
                        );
                        foreach (var zone in dr.AverageCcuServerList.OrderBy(o => o.GameZone).ToList())
                        {
                            row.Cells.Add(UIHelpers.CreateTableCell(Converter.ToString(zone.Average), HorizontalAlign.Center, css));
                        }
                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }
        private Table getCcuMax()
        {
            List<Ccu> dataList = new List<Ccu>(ccuData.Count);

            ccuData.ForEach((item) =>
            {
                dataList.Add(new Ccu(item));
            });

            //List<Ccu> dataList = new List<Ccu>(paramDt);
            foreach (Ccu ccuItem in dataList)
            {
                ccuItem.Timestamp = ConverterWorkData.truncateTime(ccuItem.Timestamp, "dd/MM/yyyy");
            }
            var gameZoneListTemp = dataList.AsParallel().Select(s => new { s.GameZone }).Distinct().OrderBy(o => o.GameZone).ToList();
            var gameZoneList = new[] { new { GameZone = "", ZoneName = "" } }.ToDictionary(d => d.GameZone, d => d.ZoneName);
            gameZoneList.Remove("");
            foreach (var zone in gameZoneListTemp)
            {
                if (gameZoneList.Keys.Contains(zone.GameZone) == false)
                {
                    gameZoneList.Add(zone.GameZone, dataList.AsParallel().Where(w => w.GameZone.Equals(zone.GameZone)).FirstOrDefault().ZoneName);
                }
            }

            Dictionary<int, List<Pcu>> gameZoneDataDic = new Dictionary<int, List<Pcu>>();
            for (int i = 0; i < gameZoneList.Count(); i++)
            {
                List<Pcu> gameZoneData = (from tb in dataList where tb.GameZone.Equals(gameZoneList.ElementAt(i).Key) group tb by new { tb.GameZone, tb.Timestamp } into grp select new Pcu { GameZone = grp.Key.GameZone, Timestamp = grp.Key.Timestamp, Max = grp.Max(t => long.Parse(t.Num)).ToString() }).ToList(); //dataList.GroupBy(g => g.Timestamp, g => g.GameZone).Where(w => w.Key.Equals(gameZoneList.ElementAt(i))).OrderBy(o => o.Timestamp).ToList();
                gameZoneDataDic.Add(int.Parse(gameZoneList.ElementAt(i).Key), gameZoneData);
            }
            var timeList = dataList.OrderByDescending(o => o.Timestamp).Select(s => s.Timestamp).Distinct().ToList();
            //var acuSumList = dataList.GroupBy(c => c.Timestamp).Select(g => new { Timestamp = g.Key, Average = g.Average(h => int.Parse(h.Num)) }).OrderBy(o => o.Timestamp).ToList();

            List<CcuMax> pcuList = new List<CcuMax>();

            for (int i = 0; i < timeList.Count; i++)
            {
                //string strDt= ConverterWorkData.ConvertFromUnixTimestamp(long.Parse(timeList[i])).ToString("dd/MM/yyyy hh:mm");
                //DateTime dtTemp = DateTime.ParseExact(strDt, "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);
                //string timeStampTemp = truncateSecond(timeList[i]);
                CcuMax cm = new CcuMax();
                foreach (KeyValuePair<int, List<Pcu>> entry in gameZoneDataDic)
                {
                    //var ccu = entry.Value.ToArray()[i];
                    Pcu pcu = null;
                    try
                    {
                        pcu = entry.Value.Where(w => w.Timestamp.Equals(timeList[i])).FirstOrDefault();
                        if (pcu == null)
                        {
                            pcu = new Pcu() { GameZone = entry.Key.ToString(), Timestamp = timeList[i], Max = "0" };
                        }
                    }
                    catch (Exception ex)
                    {

                        pcu = new Pcu() { GameZone = entry.Key.ToString(), Timestamp = timeList[i], Max = "0" };
                    }

                    cm.CcuMaxServerList.Add(pcu);
                }
                try
                {
                    var pcuSum = (from tb in cm.CcuMaxServerList group tb by new { tb.Timestamp } into grp select new { PcuSum = grp.Sum(t => long.Parse(t.Max)) }).FirstOrDefault();
                    cm.PcuSum = pcuSum.PcuSum.ToString();
                }
                catch (Exception ex)
                {
                    cm.PcuSum = "";
                }
                cm.DateTime = ConverterWorkData.kindUnixTimeStampToKindDateTime(long.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local);
                cm.Date = ConverterWorkData.kindUnixTimeStampToKindDateTime(long.Parse(timeList[i]), DateTimeKind.Local, DateTimeKind.Local).ToString("dd/MM/yyyy");
                cm.TimeStamp = long.Parse(timeList[i]);
                pcuList.Add(cm);
            }
            string startTime = timeList[0];

            //DataTable dt = ConverterWorkData.ToDataTable(pcuList, 2, gameZoneList.Count());

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Thời gian",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tổng pcu",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    //UIHelpers.CreateTableCell("CcuServerList",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[5].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[6].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                }
            );
            foreach (var zone in gameZoneList)
            {
                rowHeader.Cells.Add(UIHelpers.CreateTableCell(zone.Value, Unit.Percentage(6), HorizontalAlign.Center, "cellHeader"));
            }
            table.Rows.Add(rowHeader);
            try
            {
                if (pcuList == null || pcuList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (var dr in pcuList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Date),HorizontalAlign.Left,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PcuSum),HorizontalAlign.Left,css)
                           }
                        );
                        foreach (var zone in dr.CcuMaxServerList.OrderBy(o => o.GameZone).ToList())
                        {
                            row.Cells.Add(UIHelpers.CreateTableCell(Converter.ToString(zone.Max), HorizontalAlign.Left, css));
                        }
                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }
        protected void countButton_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            if (countTypeDropDownList.SelectedValue.Equals("0"))
            {
                dataPanel.Controls.Clear();
                dataPanel.Controls.Add(getCcuRealTime());
            }
            else
                if (countTypeDropDownList.SelectedValue.Equals("1"))
                {
                    dataPanel.Controls.Clear();
                    dataPanel.Controls.Add(getCcuAverage());
                }
                else
                    if (countTypeDropDownList.SelectedValue.Equals("2"))
                    {
                        dataPanel.Controls.Clear();
                        dataPanel.Controls.Add(getCcuMax());
                    }

            watch.Stop();
            double elapsedMS = watch.ElapsedMilliseconds;
            measureLB.Text = elapsedMS.ToString() + "miliseconds";

            WebDB.WriteLog(_User.UserName, Request.UserHostAddress, "Count " + countTypeDropDownList.SelectedItem.Text + " từ ngày:" + countToolBar.beginDateTextBox.Text + " đến ngày:" + countToolBar.toDateTextBox.Text);

        }


        protected void Button1_Click(object sender, EventArgs e)
        {
            string day = DateTime.Now.ToString("MM/dd/yyyy");
            // day = "04/08/2015";
            bool s = WebDB_N.InsertCcuCasToSqlserver(day);
            WebDB_N.checkCCUToday(DateTime.Today);
        }

        protected void loadButton2_Click(object sender, EventArgs e)
        {

            DateTime dtFormDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.beginDateTextBox.Text);
            DateTime dtToDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.toDateTextBox.Text);
            List<DateTime> dateTimeList = IDAdmin.Common.ConverterWorkData.getDateListBetween(dtFormDate, dtToDate);
            //ccuData = WebDB.getCcu(dateTimeList)

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            if (countTypeDropDownList.SelectedValue.Equals("0"))
            {
                dataPanel.Controls.Clear();
                dataPanel.Controls.Add(_getCCUNow(dateTimeList));
            }
            else
                if (countTypeDropDownList.SelectedValue.Equals("1"))
                {
                    dataPanel.Controls.Clear();
                    dataPanel.Controls.Add(getCCUAVG(dateTimeList));
                }
                else
                    if (countTypeDropDownList.SelectedValue.Equals("2"))
                    {
                        dataPanel.Controls.Clear();
                        dataPanel.Controls.Add(getCCUMaximun(dateTimeList));
                    }

            watch.Stop();
            double elapsedMS = watch.ElapsedMilliseconds;
            measureLB.Text = elapsedMS.ToString() + "miliseconds";

            WebDB.WriteLog(_User.UserName, Request.UserHostAddress, "Count " + countTypeDropDownList.SelectedItem.Text + " từ ngày:" + countToolBar.beginDateTextBox.Text + " đến ngày:" + countToolBar.toDateTextBox.Text);

        }


        private Table getCCUNow(List<DateTime> dateTimeList)
        {
            Table table = new Table();
            Dictionary<string, List<Ccu>> ccuList = WebDB_N.getFullCcu(dateTimeList);
            table.CssClass = "table1";
            TableRow rowHeader = new TableRow();
            int index = 0;
            string css;
            int stt = 0;

            DateTime fromDt = dateTimeList[0];
            DateTime weedday = AddWorkdays(fromDt, -7);
            DateTime montday = AddWorkdays(fromDt, -30);
            DateTime yesday = AddWorkdays(fromDt, -1);

            Dictionary<string, Dictionary<DateTime, int>> ListTodayCCU = new Dictionary<string, Dictionary<DateTime, int>>();
            Dictionary<string, Dictionary<DateTime, int>> ListYesterdayCCU = new Dictionary<string, Dictionary<DateTime, int>>();
            Dictionary<string, Dictionary<DateTime, int>> ListWeekagoCCU = new Dictionary<string, Dictionary<DateTime, int>>();
            Dictionary<string, Dictionary<DateTime, int>> ListMonthagoCCU = new Dictionary<string, Dictionary<DateTime, int>>();

            for (int z = 0; z < ccuList.Count; z++)
            {
                Dictionary<DateTime, int> todayCCU = new Dictionary<DateTime, int>();
                Dictionary<DateTime, int> yesterdayCCU = new Dictionary<DateTime, int>();
                Dictionary<DateTime, int> weekagoCCU = new Dictionary<DateTime, int>();
                Dictionary<DateTime, int> monthagoCCU = new Dictionary<DateTime, int>();
                foreach (var itemccu in ccuList.ElementAt(z).Value)
                {
                    if (itemccu.datetime.ToString("yyyy-MM-dd") == fromDt.ToString("yyyy-MM-dd"))
                    {
                        todayCCU.Add(itemccu.datetime, Convert.ToInt32(itemccu.Num));
                    }
                    else if (itemccu.datetime.ToString("yyyy-MM-dd") == yesday.ToString("yyyy-MM-dd"))
                    {
                        yesterdayCCU.Add(itemccu.datetime, Convert.ToInt32(itemccu.Num));
                    }
                    else if (itemccu.datetime.ToString("yyyy-MM-dd") == weedday.ToString("yyyy-MM-dd"))
                    {
                        weekagoCCU.Add(itemccu.datetime, Convert.ToInt32(itemccu.Num));
                    }
                    else
                    {
                        monthagoCCU.Add(itemccu.datetime, Convert.ToInt32(itemccu.Num));
                    }
                }
                ListTodayCCU.Add(ccuList.ElementAt(z).Key, todayCCU);
                ListYesterdayCCU.Add(ccuList.ElementAt(z).Key, yesterdayCCU);
                ListWeekagoCCU.Add(ccuList.ElementAt(z).Key, weekagoCCU);
                ListMonthagoCCU.Add(ccuList.ElementAt(z).Key, monthagoCCU);
            }

            //header table           
            rowHeader.Cells.AddRange
                (
                    new TableCell[]
                    {     
                        UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                        UIHelpers.CreateTableCell("Thời gian",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                        UIHelpers.CreateTableCell("Tổng cuu tháng trước",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                        UIHelpers.CreateTableCell("Tổng cuu tuần trước",Unit.Percentage(10),HorizontalAlign.Center, "cellHeader"),  
                        UIHelpers.CreateTableCell("Tổng cuu ngày trước",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                        UIHelpers.CreateTableCell("Tổng cuu hiện tại",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                    }
                );
            for (int i = 0; i < ListTodayCCU.Count; i++)
            {
                rowHeader.Cells.Add(UIHelpers.CreateTableCell(ListTodayCCU.ElementAt(i).Key.ToString(), Unit.Percentage(6), HorizontalAlign.Center, "cellHeader"));
            }
            table.Rows.Add(rowHeader);               
            //content table
            int a = 0;
            int _index = 288 - ListTodayCCU.Values.ElementAt(0).Count;
            foreach (var item in ListTodayCCU.ElementAt(0).Value)
            {
                stt += 1;
                css = stt % 2 == 0 ? "cell1" : "cell2";
                int totalMonth = 0;
                int totalWeek = 0;
                int totalYesterday = 0;
                int totalNow = 0;
                for (int i = 0; i < ListTodayCCU.Count; i++)  
                {
                    totalMonth += ListMonthagoCCU.Count!=0 && ListMonthagoCCU.ElementAt(i).Value.Count == 288 ? ListMonthagoCCU.ElementAt(i).Value.ElementAt(_index + a).Value : 0;
                    totalWeek += ListWeekagoCCU.Count!=0 && ListWeekagoCCU.ElementAt(i).Value.Count == 288 ?ListWeekagoCCU.ElementAt(i).Value.ElementAt(_index + a).Value : 0;
                    totalYesterday +=  ListYesterdayCCU.Count!=0 && ListYesterdayCCU.ElementAt(i).Value.Count == 288 ?ListYesterdayCCU.ElementAt(i).Value.ElementAt(_index + a).Value : 0;
                    totalNow += ListTodayCCU.ElementAt(i).Value.Count > 0 ? ListTodayCCU.ElementAt(i).Value.ElementAt(a).Value : 0;                
                }
              
                TableRow row = new TableRow();
                row.Cells.AddRange
                (
                    new TableCell[]
                    {
                        UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(item.Key),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(totalMonth.ToString(),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(totalWeek.ToString(), HorizontalAlign.Center, css),
                        UIHelpers.CreateTableCell(totalYesterday.ToString(),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(totalNow.ToString(),HorizontalAlign.Center,css)
                    }
                );
              
                for (int j = 0; j < ListTodayCCU.Count; j++)
                {
                    row.Cells.Add(UIHelpers.CreateTableCell(ListTodayCCU.ElementAt(j).Value.Count > 0 ? ListTodayCCU.ElementAt(j).Value.ElementAt(a).Value.ToString() : "0", Unit.Percentage(6), HorizontalAlign.Center, css));
                }
                table.Rows.Add(row);
                a++;          
            }
            
            return table;
        }

        //test
        private Table _getCCUNow(List<DateTime> dateTimeList)
        {
            Table table = new Table();
            Dictionary<string, List<Ccu>> ccuList = WebDB_N.getFullCcu(dateTimeList);
            table.CssClass = "table1";
            TableRow rowHeader = new TableRow();            
            string css;
            int stt = 0;

            DateTime fromDt = dateTimeList[0];
            DateTime weedday = AddWorkdays(fromDt, -7);
            DateTime montday = AddWorkdays(fromDt, -30);
            DateTime yesday = AddWorkdays(fromDt, -1);

            Dictionary<string, Dictionary<DateTime, int>> ListTodayCCU = new Dictionary<string, Dictionary<DateTime, int>>();
            Dictionary<string, Dictionary<DateTime, int>> ListYesterdayCCU = new Dictionary<string, Dictionary<DateTime, int>>();
            Dictionary<string, Dictionary<DateTime, int>> ListWeekagoCCU = new Dictionary<string, Dictionary<DateTime, int>>();
            Dictionary<string, Dictionary<DateTime, int>> ListMonthagoCCU = new Dictionary<string, Dictionary<DateTime, int>>();

            for (int z = 0; z < ccuList.Count; z++)
            {
                Dictionary<DateTime, int> todayCCU = new Dictionary<DateTime, int>();
                Dictionary<DateTime, int> yesterdayCCU = new Dictionary<DateTime, int>();
                Dictionary<DateTime, int> weekagoCCU = new Dictionary<DateTime, int>();
                Dictionary<DateTime, int> monthagoCCU = new Dictionary<DateTime, int>();
                foreach (var itemccu in ccuList.ElementAt(z).Value)
                {
                    if (itemccu.datetime.ToString("yyyy-MM-dd") == fromDt.ToString("yyyy-MM-dd"))
                    {
                        todayCCU.Add(itemccu.datetime, Convert.ToInt32(itemccu.Num));
                    }
                    else if (itemccu.datetime.ToString("yyyy-MM-dd") == yesday.ToString("yyyy-MM-dd"))
                    {
                        yesterdayCCU.Add(itemccu.datetime, Convert.ToInt32(itemccu.Num));
                    }
                    else if (itemccu.datetime.ToString("yyyy-MM-dd") == weedday.ToString("yyyy-MM-dd"))
                    {
                        weekagoCCU.Add(itemccu.datetime, Convert.ToInt32(itemccu.Num));
                    }
                    else
                    {
                        monthagoCCU.Add(itemccu.datetime, Convert.ToInt32(itemccu.Num));
                    }
                }
                ListTodayCCU.Add(ccuList.ElementAt(z).Key, todayCCU);
                ListYesterdayCCU.Add(ccuList.ElementAt(z).Key, yesterdayCCU);
                ListWeekagoCCU.Add(ccuList.ElementAt(z).Key, weekagoCCU);
                ListMonthagoCCU.Add(ccuList.ElementAt(z).Key, monthagoCCU);
            }

            //header table           
            rowHeader.Cells.AddRange
                (
                    new TableCell[]
                    {     
                        UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                        UIHelpers.CreateTableCell("Thời gian",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                        UIHelpers.CreateTableCell("Tổng cuu tháng trước",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                        UIHelpers.CreateTableCell("Tổng cuu tuần trước",Unit.Percentage(10),HorizontalAlign.Center, "cellHeader"),  
                        UIHelpers.CreateTableCell("Tổng cuu ngày trước",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                        UIHelpers.CreateTableCell("Tổng cuu hiện tại",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                    }
                );
            for (int i = 0; i < ListTodayCCU.Count; i++)
            {
                rowHeader.Cells.Add(UIHelpers.CreateTableCell(ListTodayCCU.ElementAt(i).Key.ToString(), Unit.Percentage(6), HorizontalAlign.Center, "cellHeader"));
            }
            table.Rows.Add(rowHeader);
            //content table           
            DateTime Today = dateTimeList[0];
            DateTime Mounthago = Today.AddDays(-30);
            DateTime Weekago = Today.AddDays(-7);
            DateTime Yesterday = Today.AddDays(-1);
            DateTime TimeLimit = Today == DateTime.Today ? DateTime.Now : Convert.ToDateTime(Today.ToString("MM/dd/yyyy 23:59:59"));
            int run_m = 0;
            int run_w = 0;
            int run_y = 0;
            int run = 0;

            for (DateTime moment = Today; moment < TimeLimit; moment = moment.AddMinutes(5))
            {              
                css = stt % 2 == 0 ? "cell1" : "cell2";
                int totalMonth = 0;
                int totalWeek = 0;
                int totalYesterday = 0;
                int totalNow = 0;
                for (int i = 0; i < ListTodayCCU.Count; i++)
                {
                    if (ListMonthagoCCU.Count != 0 && run_m < (ListMonthagoCCU.ElementAt(i).Value.Count - 1) && ListMonthagoCCU.ElementAt(i).Value.Count != 0 && ListMonthagoCCU.ElementAt(i).Value.ElementAt(run_m).Key.ToString("yyyy-MM-dd HH:MM") == Mounthago.ToString("yyyy-MM-dd HH:MM"))
                    {
                        if (run_m < (ListMonthagoCCU.ElementAt(i).Value.Count - 1))
                        {
                            totalMonth += ListMonthagoCCU.Count != 0 ? ListMonthagoCCU.ElementAt(i).Value.ElementAt(run_m).Value : 0;
                            
                        }
                    }
                    if (ListWeekagoCCU.Count != 0 && run_w < (ListWeekagoCCU.ElementAt(i).Value.Count - 1) && ListWeekagoCCU.ElementAt(i).Value.Count != 0 && ListWeekagoCCU.ElementAt(i).Value.ElementAt(run_w).Key.ToString("yyyy-MM-dd HH:MM") == Weekago.ToString("yyyy-MM-dd HH:MM"))
                    {
                        if (run_w < (ListWeekagoCCU.ElementAt(i).Value.Count - 1))
                        {
                            totalWeek += ListWeekagoCCU.Count != 0 ? ListWeekagoCCU.ElementAt(i).Value.ElementAt(run_w).Value : 0;
                           
                        }
                    }
                    if (ListYesterdayCCU.Count != 0 && run_y < (ListYesterdayCCU.ElementAt(i).Value.Count - 1) && ListYesterdayCCU.ElementAt(i).Value.Count != 0 && ListYesterdayCCU.ElementAt(i).Value.ElementAt(run_y).Key.ToString("yyyy-MM-dd HH:MM") == Yesterday.ToString("yyyy-MM-dd HH:MM"))
                    {
                        if (run_y < (ListYesterdayCCU.ElementAt(i).Value.Count - 1))
                        {
                            totalYesterday += ListYesterdayCCU.Count != 0 ? ListYesterdayCCU.ElementAt(i).Value.ElementAt(run_y).Value : 0;
                            run_y = i == (ListTodayCCU.Count - 1) ? (run_y + 1) : run_y;
                        }
                    }
                    if (ListTodayCCU.Count != 0 && run < (ListTodayCCU.ElementAt(i).Value.Count - 1) && ListTodayCCU.ElementAt(i).Value.Count != 0 && ListTodayCCU.ElementAt(i).Value.ElementAt(run).Key.ToString("yyyy-MM-dd HH:MM") == moment.ToString("yyyy-MM-dd HH:MM"))
                    {                        
                        if (run < (ListTodayCCU.ElementAt(i).Value.Count - 1))
                        {                            
                            totalNow += ListTodayCCU.ElementAt(i).Value.Count > 0 ? ListTodayCCU.ElementAt(i).Value.ElementAt(run).Value : 0;
                        }                       
                    }
                    run_y = i == (ListTodayCCU.Count - 1) ? (run_y + 1) : run_y;
                    run_w = i == (ListTodayCCU.Count - 1) ? (run_w + 1) : run_w;
                    run_m = i == (ListTodayCCU.Count - 1) ? (run_m + 1) : run_m;
                    run = i == (ListTodayCCU.Count - 1) ? (run + 1) : run;
                }
                Today = Today.AddMinutes(5);
                Mounthago = Mounthago.AddMinutes(5);
                Weekago = Weekago.AddMinutes(5);
                Yesterday = Yesterday.AddMinutes(5);

                TableRow row = new TableRow();
                row.Cells.AddRange
                (
                    new TableCell[]
                    {
                        UIHelpers.CreateTableCell(run.ToString(),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(Converter.ToString(moment),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(totalMonth.ToString(),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(totalWeek.ToString(), HorizontalAlign.Center, css),
                        UIHelpers.CreateTableCell(totalYesterday.ToString(),HorizontalAlign.Center,css),
                        UIHelpers.CreateTableCell(totalNow.ToString(),HorizontalAlign.Center,css)
                    }
                );

                for (int j = 0; j < ListTodayCCU.Count; j++)
                {
                    row.Cells.Add(UIHelpers.CreateTableCell(ListTodayCCU.ElementAt(j).Value.Count > 0 && (run - 1) < (ListTodayCCU.ElementAt(j).Value.Count - 1) && ListTodayCCU.ElementAt(j).Value.ElementAt(run - 1).Key.ToString("yyyy-MM-dd HH:MM") == moment.ToString("yyyy-MM-dd HH:MM") ? ListTodayCCU.ElementAt(j).Value.ElementAt(run - 1).Value.ToString() : "0", Unit.Percentage(6), HorizontalAlign.Center, css)); //ListTodayCCU.ElementAt(j).Value.Count > 0 ? ListTodayCCU.ElementAt(j).Value.ElementAt(run).Value.ToString() : 
                }
                table.Rows.Add(row);
            }

            return table;
        }
       //end test







        private Table getCCUAVG(List<DateTime> dateTimeList)
        {
            Table table = new Table();
            List<Ccu> ccuList = WebDB_N.getAVGCcu(dateTimeList);
            table.CssClass = "table1";

            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                            {     
                                UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                                UIHelpers.CreateTableCell("Thời gian",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                                
                            }
            );

            try
            {
                if (ccuList == null || ccuList.Count == 0)
                {
                    table.Rows.Add(rowHeader);
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    string css;
                    int stt = 0;
                    rowHeader.Cells.AddRange
                    (
                        new TableCell[]
                            {   
                                UIHelpers.CreateTableCell("Tổng ACU",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                            }
                    );
                    foreach (var item in listServer)
                    {
                        rowHeader.Cells.AddRange
                        (
                            new TableCell[]
                            {   
                                UIHelpers.CreateTableCell("ACU - " + item.zonename.ToString() ,Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                            }
                        );
                    }
                    table.Rows.Add(rowHeader);

                    //add data to table
                    int i = 0;
                    int t = 0;
                    foreach (var ccu in ccuList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();

                        int total = 0;
                        foreach (var item in listServer)
                        {
                            total += item.gamezone == Convert.ToInt32(ccuList[t].GameZone) ? Convert.ToInt32(ccuList[t].Num) : 0;

                            if (item.gamezone == Convert.ToInt32(ccuList[t].GameZone) && t < ccuList.Count - 1)
                            {
                                t++;
                            }
                        }

                        row.Cells.AddRange
                        (
                            new TableCell[]
                                {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(ccuList[i].datetime.ToString("dd-MM-yyyy"),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(total.ToString(),HorizontalAlign.Center,css)
                                }
                        );

                        foreach (var item in listServer)
                        {
                            row.Cells.Add(UIHelpers.CreateTableCell(item.gamezone == Convert.ToInt32(ccuList[i].GameZone) ? ccuList[i].Num.ToString() : "0", HorizontalAlign.Center, css));
                            if (item.gamezone == Convert.ToInt32(ccuList[i].GameZone) && i < ccuList.Count - 1)
                            {
                                i++;
                            }
                        }
                        table.Rows.Add(row);
                        if (i >= ccuList.Count - 1) {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return table;
        }

        private Table getCCUMaximun(List<DateTime> dateTimeList)
        {
            Table table = new Table();
            List<Ccu> ccuList = WebDB_N.getMAxCcu(dateTimeList);
            table.CssClass = "table1";

            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                            {     
                                UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                                UIHelpers.CreateTableCell("Thời gian",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                                
                            }
            );

            try
            {
                if (ccuList == null || ccuList.Count == 0)
                {
                    table.Rows.Add(rowHeader);
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    string css;
                    int stt = 0;
                    rowHeader.Cells.AddRange
                    (
                        new TableCell[]
                            {   
                                UIHelpers.CreateTableCell("Tổng PCU",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                            }
                    );
                    foreach (var item in listServer)
                    {
                        rowHeader.Cells.AddRange
                        (
                            new TableCell[]
                            {   
                                UIHelpers.CreateTableCell("PCU - " + item.zonename.ToString() ,Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                            }
                        );
                    }
                    table.Rows.Add(rowHeader);

                    //add data to table
                    int i = 0;
                    int t = 0;
                    foreach (var ccu in ccuList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();

                        int total = 0;
                        foreach (var item in listServer)
                        {
                            total += item.gamezone == Convert.ToInt32(ccuList[t].GameZone) ? Convert.ToInt32(ccuList[t].Num)  : 0;

                            if (item.gamezone == Convert.ToInt32(ccuList[t].GameZone) && t < ccuList.Count - 1)
                            {
                                t++;
                            }
                        }

                        row.Cells.AddRange
                        (
                            new TableCell[]
                                {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(ccuList[i].datetime.ToString("dd-MM-yyyy"),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(total.ToString(),HorizontalAlign.Center,css)
                                }
                        );

                        foreach (var item in listServer)
                        {
                            row.Cells.Add(UIHelpers.CreateTableCell(item.gamezone == Convert.ToInt32(ccuList[i].GameZone) ? ccuList[i].Num.ToString() : "0", HorizontalAlign.Center, css));
                            if (item.gamezone == Convert.ToInt32(ccuList[i].GameZone) && i < ccuList.Count - 1)
                            {
                                i++;
                            }                           
                        }
                        table.Rows.Add(row);
                        if (i >= ccuList.Count - 1)
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return table;
        }
        public static DateTime AddWorkdays(DateTime originalDate, int workDays)
        {
            DateTime tmpDate = originalDate;
            int a = workDays > 0 ? 1 : -1;
            while (workDays != 0)
            {
                tmpDate = tmpDate.AddDays(a);
                workDays -= a;
                //workDays--;
            }
            return tmpDate;
        }
    }
}